package fl.ass.service.api;

import cmm.comm.facade.upload.api.IUploadApiService;
import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.comm.facade.upload.dto.SysUlFilesRecDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.finance.api.IFinPayDtlApiService;
import cn.fl.finance.condition.FinPayDtlQC;
import cn.fl.finance.dto.FinPayDtlDTO;
import cn.fl.project.condition.PrjPrdPaySchDQueryCondition;
import com.alibaba.fastjson.JSON;
import com.lionbridge.activiti.WorkflowClient;
import fl.ass.facade.api.IAssTrailCarApi;
import fl.ass.facade.api.INevTrailerApplicationFlowFactoryApi;
import fl.ass.facade.constant.AssFileConstant;
import fl.ass.facade.constant.InterfaceConstants;
import fl.ass.facade.dto.*;
import fl.ass.service.dao.AssTrailCarDMapper;
import fl.ass.service.po.PrjPrdPaySchD;
import fl.ass.service.service.IAssParkingMgService;
import fl.ass.service.service.IAssTrailCarDService;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.FlowCompleteParamsDTO;
import fl.flow.facade.flow.service.impl.FlowBusnessServiceImpl;
import fl.flow.service.flow.service.ISysFlowSHService;
import fl.inf.facade.api.IBFSApiService;
import fl.inf.facade.api.IWarrantApiService;
import fl.inf.facade.dto.InfBfsPayDTO;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 新能源拖车申请流程回调接口实现类
 * @author liwenjun
 
 */
@Service
public class NevTrailerApplicationFlowFactoryApi extends FlowBusnessServiceImpl implements INevTrailerApplicationFlowFactoryApi {

	/**
	 * 流程启动历史服务
	 */
	@Autowired
	private ISysFlowSHService sysFlowSHService;
	/**
	 * 拖车服务
	 */
	@Autowired
	private IAssTrailCarApi assTrailCarApi;
	/**
	 * 上传下载服务
	 */
	@Autowired
	private IUploadApiService uploadApiService;

	/**
	 *
	 */
	@Autowired
	private AssTrailCarDMapper assTrailCarDMapper;
	/**
	 *权证
	 */
	@Autowired
	private IWarrantApiService warrantApiService;
	
	@Autowired
	private IBFSApiService bFSApiService;
	@Value("${pay.environment}")
    private String env;
	@Autowired
	private IFinPayDtlApiService finPayDtlApiService;

	@Autowired
    private IAssParkingMgService assParkingMgService;
	@Autowired
    private IAssTrailCarDService assTrailCarDService;

	@Override
	public Map<String, Object> executeBefore(FlowCompleteParamsDTO flowCompleteParamsDTO) throws BaseException {
		Map<String, Object> parms = new HashMap<String, Object>();
		String procDefKey = flowCompleteParamsDTO.getProcDefKey();//流程KEY
		String taskDefKey = flowCompleteParamsDTO.getTaskDefKey();//任务KEY
		String branchKey = flowCompleteParamsDTO.getBranchKey();//分支KEY
		String procInstId = flowCompleteParamsDTO.getProcInstId();
		Long trailer_id = flowCompleteParamsDTO.getBusinessKey();
        BaseLogUtils.newLogger("拖车申请流程回调接口").setBussinessId("trailer_id:" + trailer_id).info();
		if("FLOW_00000013_017_001".equals(procDefKey)&&StringUtils.isNotEmpty(taskDefKey)&&StringUtils.isNotEmpty(branchKey)){
			MessageDTO<String>  result;
			MessageDTO<AssTrailCarMDTO> messageDTO  = assTrailCarApi.findAssTrailCarMasterById(trailer_id);
			AssTrailCarMDTO assTrailCarMDTO = messageDTO.getData();
			List<AssTrailCarDInfDTO> infoList = new ArrayList<AssTrailCarDInfDTO>();
			//拖车明细数据
			List<Long> detailIdList = new ArrayList<Long>();
			List<AssTrailCarDDTO> assTrailCarDDTOList = assTrailCarApi.findTrailCarDetailListById(trailer_id).getDatas();
			for (AssTrailCarDDTO assTrailCarDDTO : assTrailCarDDTOList) {
				detailIdList.add(assTrailCarDDTO.getId());
			}
			
			if(branchKey.equals("FLOW_00000013_017_001_004_001")){//事业部审核（重卡）:点击通过
				/**
				 * TODO 1.检验借款金额是否=0
				 */
				int BACK_AMT_FLAG = BaseConstant.IS_YESNO_NO;
				for (AssTrailCarDDTO assTrailCarDDTO : assTrailCarDDTOList) {
					if (assTrailCarDDTO.getBackAmt() != null) {
						Long backAmt = assTrailCarDDTO.getBackAmt();
						if (backAmt/100> 0) {
							BACK_AMT_FLAG = BaseConstant.IS_YESNO_YES;
						}
					}
				}
				parms.put("BACK_AMT_FLAG", BACK_AMT_FLAG);
				
			}else if(branchKey.equals("FLOW_00000013_017_001_015_001")){//法务经理（汽车金融 ）:点击通过
				/**
				 * TODO 1.检验借款金额是否>=6000
				 */
				
				int BACK_AMT_FLAG = BaseConstant.IS_YESNO_NO;
				for (AssTrailCarDDTO assTrailCarDDTO : assTrailCarDDTOList) {
					if (assTrailCarDDTO.getBackAmt() != null) {
						Long backAmt = assTrailCarDDTO.getBackAmt();
						if (backAmt/100 >= 6000) {
							BACK_AMT_FLAG = BaseConstant.IS_YESNO_YES;
						}
					}
				}
				parms.put("BACK_AMT_FLAG", BACK_AMT_FLAG);
				 
			}else if(branchKey.equals("FLOW_00000013_017_001_006_001")||branchKey.equals("FLOW_00000013_017_001_020_001")){//财务付款:点击通过FLAG=1
				/**
				 * TODO 1.检验是否填写实际付款时间及金额
				 */
				MessageDTO<AssTrailCarDInfDTO> messageDto = assTrailCarApi.findTrailCarDetailListByDetailIds(detailIdList);
				if (messageDto.isSuccess() &&  messageDto.getDatas() != null && messageDto.getDatas().size() >0) {
					infoList = messageDto.getDatas();
				for (AssTrailCarDInfDTO assTrailCarDInfDTO : infoList) {
					if (assTrailCarDInfDTO.getActPayDt() == null || "".equals(assTrailCarDInfDTO.getActPayDt())||assTrailCarDInfDTO.getActPayAmt() == null||"".equals(assTrailCarDInfDTO.getActPayAmt())) {
						throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "请填写实际付款时间及金额");
					}
				}
				}else{
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "拖车实际明细信息不存在.");
				}
			}else if(branchKey.equals("FLOW_00000013_017_001_008_001")){//记录拖车状态（重卡）、呈报人拖回标记（汽车金融）：点击通过
				/**
				 * TODO 1.检验是否记录了拖车状态（BACKED_FLAG_CD 1：已拖回  2：未拖回 3：无法拖回）
				 */
				int BACK_FLAG_CD_1 = BaseConstant.IS_YESNO_NO;
				int BACK_FLAG_CD_0 = BaseConstant.IS_YESNO_YES;
				ProductStatusLogDTO proDTO = null;
				List<ProductStatusLogDTO> proList = new ArrayList<ProductStatusLogDTO>();
				if(assTrailCarDDTOList != null && assTrailCarDDTOList.size() > 0){
					for (AssTrailCarDDTO assTrailCarDDTOTemp : assTrailCarDDTOList) {
						System.out.println(assTrailCarDDTOTemp.getBackedFlagCd()+"+++++++++++++assTrailCarDDTOTemp.getBackedFlagCd()+++++++++");
                        BaseLogUtils.newLogger("修改拖车状态start").setBussinessId("detailId:" + assTrailCarDDTOTemp.getId()).info();
						if(StringUtils.isEmpty(assTrailCarDDTOTemp.getBackedFlagCd()) || assTrailCarDDTOTemp.getBackedFlagCd().equals("0") || assTrailCarDDTOTemp.getBackedFlagCd().toString() == "0"){
							throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "请标记拖车状态");
						}
						if (assTrailCarDDTOTemp.getBackedFlagCd().equals(InterfaceConstants.BACK_FLAG_CD_1)||assTrailCarDDTOTemp.getBackedFlagCd().toString() == "1") {//状态是否为已拖回
							BACK_FLAG_CD_1 = BaseConstant.IS_YESNO_YES;
						}
						if(assTrailCarDDTOTemp.getBackedFlagCd().equals(InterfaceConstants.BACK_FLAG_CD_2) || assTrailCarDDTOTemp.getBackedFlagCd().toString() == "2"||assTrailCarDDTOTemp.getBackedFlagCd().equals(InterfaceConstants.BACK_FLAG_CD_3)||assTrailCarDDTOTemp.getBackedFlagCd().toString() == "3"){
							BACK_FLAG_CD_0 = BaseConstant.IS_YESNO_NO;
							if(assTrailCarDDTOTemp.getBackedFlagCd().equals(InterfaceConstants.BACK_FLAG_CD_2)){
								proDTO = new ProductStatusLogDTO();
								proDTO.setCurrentStatus(InterfaceConstants.PAY_STATUS_CD_S01);
								proDTO.setPrjPrdId(assTrailCarDDTOTemp.getPrjPrdDtlId());
								proDTO.setOpCode(InterfaceConstants.OP_CODE_OP0020);
								proDTO.setProcessInstanceCode(procDefKey);
								proDTO.setProcessInstanceId(procInstId);
								proList.add(proDTO);
							}
							if(assTrailCarDDTOTemp.getBackedFlagCd().equals(InterfaceConstants.BACK_FLAG_CD_3)){
								proDTO = new ProductStatusLogDTO();
								proDTO.setCurrentStatus(InterfaceConstants.PAY_STATUS_CD_S010601);
								proDTO.setPrjPrdId(assTrailCarDDTOTemp.getPrjPrdDtlId());
								proDTO.setOpCode(InterfaceConstants.OP_CODE_OP0020);
								proDTO.setProcessInstanceCode(procDefKey);
								proDTO.setProcessInstanceId(procInstId);
								proList.add(proDTO);
							}	
						}
					}
					if (!proList.isEmpty() && proList.size() > 0) {
                        BaseLogUtils.newLogger("更新支付表状态start").info();
						result = this.assTrailCarApi.updatePayStatus(proList);
						if (!result.isSuccess()) {
							throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "更新支付表的状态失败.");
						}
                        BaseLogUtils.newLogger("更新支付表状态end").info();
					}
				}else{
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "拖车明细信息不存在.");
				}
				parms.put("BACK_FLAG_CD_1",BACK_FLAG_CD_1);
				parms.put("BACK_FLAG_CD_0",BACK_FLAG_CD_0);
				if (BACK_FLAG_CD_1 == 1) {
                    Long recentParkMgId = this.assParkingMgService.getRecentParkMg(assTrailCarMDTO.getParkId());
                    if (StringUtils.isNotEmpty(recentParkMgId)) {
                        String[] str = {String.valueOf(recentParkMgId)};
                        parms.put("nextAssignee", str);
                    } else {
                        parms.put("nextAssignee", null);
                    }
				}
				parms.put("REJECT", BaseConstant.IS_YESNO_NO);
			}else if(branchKey.equals("FLOW_00000013_017_001_017_002") || branchKey.equals("FLOW_00000013_017_001_009_002")){//资产管理员入库/资产管理员入库1：驳回
				parms.put("REJECT", BaseConstant.IS_YESNO_YES);
			}else if(branchKey.equals("FLOW_00000013_017_001_011_001")||branchKey.equals("FLOW_00000013_017_001_018_001")){//优车系统管理员核查入库情况、优车系统管理员核查入库情况1:点击已入库
				/**
				 * TODO 1.修改入库状态、入库时间等:已入库
				 *      2.修改入库单的状态：已验证
				 *      3.修改支付表中的拖车状态、拖回日期：已拖回
				 */
				if(assTrailCarDDTOList != null && assTrailCarDDTOList.size() > 0){
					for (AssTrailCarDDTO assTrailCarDDTO : assTrailCarDDTOList) {
						assTrailCarDDTO.setIsEnter(InterfaceConstants.IS_ENTER_1);
						assTrailCarDDTO.setEnterTm(new Date());
						assTrailCarDDTO.setActBackDt(new Date());
					    result = assTrailCarApi.updateAssTrailCarDetailInfo(assTrailCarDDTO);
						if (!result.isSuccess()) {
							throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "修改入库状态失败.");
						}
					}
					MessageDTO<AssTrailCarDInfDTO> assTrailCarDInfDTO = assTrailCarApi.findTrailCarDetailListByDetailIds(detailIdList);
					if (assTrailCarDInfDTO.isSuccess()&& assTrailCarDInfDTO.getDatas()!=null && assTrailCarDInfDTO.getDatas().size() > 0) {
						infoList = assTrailCarDInfDTO.getDatas();
						for (AssTrailCarDInfDTO assTrailCarDInfDTOTemp : infoList) {
							assTrailCarDInfDTOTemp.setActBackDt(new Date());
							result = assTrailCarApi.modifyTrailCarDInf(assTrailCarDInfDTOTemp);
							if (!result.isSuccess()) {
								throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "修改实际拖回日期失败.");
							}
						}
						
					}else{
						throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "查询信息失败");
					}
				}else{
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "拖车明细信息不存在.");
				}
				int BACK_AMT_FLAG = BaseConstant.IS_YESNO_NO;
				for (AssTrailCarDDTO assTrailCarDDTO : assTrailCarDDTOList) {
					if (assTrailCarDDTO.getBackAmt() != null) {
						Long backAmt = assTrailCarDDTO.getBackAmt();
						if (backAmt/100 > 0) {
							BACK_AMT_FLAG = BaseConstant.IS_YESNO_YES;
						}
					}
				}
				parms.put("BACK_AMT_FLAG", BACK_AMT_FLAG);
				List<ProductStatusLogDTO> proList = new ArrayList<ProductStatusLogDTO>();
				ProductStatusLogDTO proDTO = null;
				if(assTrailCarDDTOList != null && assTrailCarDDTOList.size() > 0){
					for (AssTrailCarDDTO assTrailCarDDTO : assTrailCarDDTOList) {
                        BaseLogUtils.newLogger("修改入库附件的状态Start").setKeys("detailId:" + assTrailCarDDTO.getId()).info();
						SysUlFilesRecQueryCondition qc = new SysUlFilesRecQueryCondition();
						qc.setPkId(String.valueOf(assTrailCarDDTO.getId()));//主数据ID
						qc.setTabNm(AssFileConstant.ASS_TRAIL_CAR_D_TABNM);//主数据表明
						qc.setSysCd(flowCompleteParamsDTO.getSysCd());//系统代码-必须条件
						qc.setCfgCd(AssFileConstant.ASS_TRAIL_CAR_CFGCD);//拖车模块
						qc.setCfgDtlCd(AssFileConstant.ASS_TRAIL_CAR_CFGDTLCD_30);//入库单
						List<SysUlFilesRecDTO> list = this.uploadApiService.searchSysUlFilesRecList(qc);
						if (list == null || list.size() < 1) {
							throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "更新入库单验证状态失败--请先上传入库单附件.");
						}else{
								qc.setAudStsCd(AssFileConstant.AUD_STS_CD_1);//验证通过
								boolean flag = this.uploadApiService.modifyAudStsCd(qc);
								if (!flag) {
									throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "更新入库单验证状态失败.");
								}
						}
                        BaseLogUtils.newLogger("修改入库附件的状态end").setKeys("detailId:" + assTrailCarDDTO.getId()).info();
						
					    proDTO = new ProductStatusLogDTO();
						proDTO.setCurrentStatus(InterfaceConstants.PAY_STATUS_CD_S010602);//已拖回
						proDTO.setPrjPrdId(assTrailCarDDTO.getPrjPrdDtlId());
						proDTO.setOpCode(InterfaceConstants.OP_CODE_OP0020);//拖车申请通过
						proDTO.setProcessInstanceCode(procDefKey);
						proDTO.setProcessInstanceId(procInstId);
						proList.add(proDTO);
					}

                    BaseLogUtils.newLogger("修改支付表状态：start").info();
					result = this.assTrailCarApi.updatePayStatus(proList);
					if (!result.isSuccess()) {
						throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "更新支付表的状态失败.");
					}
                    BaseLogUtils.newLogger("修改支付表状态：end").info();

					for (AssTrailCarDDTO assTrailCarDDTO : assTrailCarDDTOList) {
                        BaseLogUtils.newLogger("支付表状态为已拖回，向权证接口传送数据start").setKeys("masterId:" + assTrailCarDDTO.getMasterId(), "detailId:" + assTrailCarDDTO.getId()).info();
                        if (assTrailCarDDTO.getBackedFlagCd().equals(InterfaceConstants.BACK_FLAG_CD_1)) {//拖回标记：已拖回
                            Long projectId = assTrailCarDDTO.getPrjId();
                            String paylistCode = assTrailCarDDTO.getPaySchNo();//支付表编号
                            String status = InterfaceConstants.PAY_STATUS_CD_S010602;
                            Date endDate = null;//结清日期可以为空
                            fl.inf.facade.dto.MessageDTO<String> response = warrantApiService.changePayStatus(projectId, paylistCode, status, endDate);
                            if (!response.isSuccess()) {
                                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "===向权证接口传送数据失败===.");
                            }
                        }
                    }
                    BaseLogUtils.newLogger("支付表状态为已拖回，向权证接口传送数据end").info();
				}	
		
			}else if( branchKey.equals("FLOW_00000013_017_001_007_001") || branchKey.equals("FLOW_00000013_017_001_012_001") || branchKey.equals("FLOW_00000013_017_001_021_001")){//财务做账、财务做账1：通过
				if(assTrailCarDDTOList != null && assTrailCarDDTOList.size() > 0){
					for (AssTrailCarDDTO assTrailCarDDTO : assTrailCarDDTOList) {
							PrjPrdPaySchD prjPrdPaySchD = new PrjPrdPaySchD();
							PrjPrdPaySchDQueryCondition con = new PrjPrdPaySchDQueryCondition();
							con.setPaySchId(assTrailCarDDTO.getPaySchId());
							con.setFeeTypCd(InterfaceConstants.FEE_TYP_CD_104);
							con.setVfFlag(1);//AR_AMT !=0  未分解
							// 拆分支付表数据
							List<PrjPrdPaySchD> list = assTrailCarDMapper.selectPrjPaySchFeeList(con);
							if (!list.isEmpty() && list.size()>0) {//已存在，做更新
                                BaseLogUtils.newLogger("更新实际拖车费用 start").setKeys(JSON.toJSONString(assTrailCarDDTO)).info();
                                this.updatePrjPrdPaySchD(assTrailCarDDTO,list.get(0));
                                BaseLogUtils.newLogger("更新实际拖车费用 end").info();
							}else{
								if(assTrailCarDDTO.getActBackAmt() != null && assTrailCarDDTO.getActBackAmt() != 0){
                                    BaseLogUtils.newLogger("插入实际拖车费用").setKeys(JSON.toJSONString(assTrailCarDDTO)).info();
									Long id = this.insertPrjPrdPaySchD(assTrailCarDDTO,prjPrdPaySchD);
                                    BaseLogUtils.newLogger("插入实际拖车费用").setKeys("id:" + id).info();
								}
						 }
					}
				}
				
			}else if(branchKey.equals("FLOW_00000013_017_001_011_002")||branchKey.equals("FLOW_00000013_017_001_018_002")){//优车系统管理员核查入库情况：驳回
                Long recentParkMgId = this.assParkingMgService.getRecentParkMg(assTrailCarMDTO.getParkId());
                if (StringUtils.isNotEmpty(recentParkMgId)) {
                    String[] str = {String.valueOf(recentParkMgId)};
                    parms.put("nextAssignee", str);
                } else {
                    parms.put("nextAssignee", null);
                }
			}else if(branchKey.equals("FLOW_00000013_017_001_013_001")||branchKey.equals("FLOW_00000013_017_001_022_001")){//财务估算保底价、保底价核算:点击通过
				/**
				 * TODO 1.检验是否填写保底价款
				 * 		2.若填写，修改拖车状态，流程通过的时间，流程结束
				 */
				//检验是否填写保底价款
                BaseLogUtils.newLogger("查询拖车实际明细信息Start").setKeys(JSON.toJSONString(detailIdList)).info();
				MessageDTO<AssTrailCarDInfDTO> assTrailCarDInfDTO = assTrailCarApi.findTrailCarDetailListByDetailIds(detailIdList);
				if (assTrailCarDInfDTO.isSuccess()&& assTrailCarDInfDTO.getDatas()!=null && assTrailCarDInfDTO.getDatas().size() > 0) {
					infoList = assTrailCarDInfDTO.getDatas();
					for (AssTrailCarDInfDTO assTrailCarDInfDTOTemp : infoList) {
						if (assTrailCarDInfDTOTemp.getBaseAmt() == null || "".equals(assTrailCarDInfDTOTemp.getBaseAmt())) {//一次性保底价
							throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "请填写保底价款");
						}
					}
				}else{
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "查询信息失败");
				}
				//this.flowSuccess(assTrailCarDDTOList);
			}
			switch (branchKey) {
			case "FLOW_00000013_017_001_013_001"://财务估算保底价:通过
				this.flowSuccess(assTrailCarDDTOList);
				break;
			case "FLOW_00000013_017_001_012_001"://财务做账1:通过
				this.flowSuccess(assTrailCarDDTOList);
				break;	
			case "FLOW_00000013_017_001_008_002"://记录拖车状态:不通过
				this.flowFail(assTrailCarDDTOList,procDefKey,procInstId);
				break;
			case "FLOW_00000013_017_001_003_002"://发起人:不通过
				this.flowFail(assTrailCarDDTOList,procDefKey,procInstId);
				break;
			case "FLOW_00000013_017_001_022_001"://乘用车保底价核算:通过
				this.flowSuccess(assTrailCarDDTOList);
				break;
			case "FLOW_00000013_017_001_005_001"://财务总监审核：提交
				this.assTrailCarDService.addFinLoadInfoAndFlowHistory(trailer_id, flowCompleteParamsDTO);
				break;
			case "FLOW_00000013_017_001_024_001"://异常处理 处理
				getDeal(trailer_id);
				break;
			case "FLOW_00000013_017_001_024_002"://异常处理 核查无误
				getAgen(trailer_id);
				break;
			default:
				break;
		   }
		}
	
		
		return parms;
	}

	@Override
	public void executeAfter(FlowCompleteParamsDTO flowCompleteParamsDTO) throws BaseException {
        String branchKey = flowCompleteParamsDTO.getBranchKey();
        String procInstId = flowCompleteParamsDTO.getProcInstId();
        if (StringUtils.isNotEmpty(branchKey)) {
            switch (branchKey) {
                case "FLOW_00000013_017_001_013_001"://财务估算保底价:通过
                    this.pass(flowCompleteParamsDTO);
                    break;
                case "FLOW_00000013_017_001_012_001"://财务做账1:通过
                    this.pass(flowCompleteParamsDTO);
                    break;
                case "FLOW_00000013_017_001_008_002"://记录拖车状态:不通过
                    this.noPass(flowCompleteParamsDTO);
                    break;
                case "FLOW_00000013_017_001_003_002"://发起人:不通过
                    this.noPass(flowCompleteParamsDTO);
                    break;
                case "FLOW_00000013_017_001_022_001"://乘用车保底价核算:通过
                    this.pass(flowCompleteParamsDTO);
                    break;
                case "FLOW_00000013_017_001_024_002"://异常处理 核查无误
                    // 核查无误后通过放款中节点
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("returnResult", "success");
                    this.passPay(procInstId, params, "auto_complete_task_loan_0");
                    break;
                default:
                    break;
            }
        }
    }
	@Override
	public String executeFlowBack(FlowCompleteParamsDTO flowCompleteParamsDTO) throws BaseException {

		String taskDefKey = flowCompleteParamsDTO.getTaskDefKey();
		Long id = flowCompleteParamsDTO.getBusinessKey();
        BaseLogUtils.newLogger("java节点Start").setKeys("taskDefKey:" + taskDefKey, "id:" + id).info();
		switch (taskDefKey) {
		case "FLOW_00000013_017_001_023"://发送网银
			List<FinPayDtlDTO> selectList = getFinPayDtlList(id);
			int flag =0;
			for (FinPayDtlDTO dto : selectList) {
                BaseLogUtils.newLogger("新能源拖车流程id&网银交易查询请求参数").setKeys(JSON.toJSONString(dto.getId())).info();
				InfBfsPayDTO ibpd = bFSApiService.selectByFlsNum(dto.getId());
                BaseLogUtils.newLogger("新能源拖车流程id&网银交易查询返回结果").setKeys(JSON.toJSONString(dto.getId()), JSON.toJSONString(ibpd)).info();
				//调用网银接口
				if(null==ibpd
						|| "payFailure".equals(ibpd.getStatus())
						|| "sendFailure".equals(ibpd.getStatus())){
					if(env.equals("pro")){
                        BaseLogUtils.newLogger("新能源拖车流程id&发送网银请求参数").setKeys(JSON.toJSONString(dto.getId())).info();
						fl.inf.facade.dto.MessageDTO<String> sendPay = bFSApiService.sendTrailCar(dto.getId());
                        BaseLogUtils.newLogger("新能源拖车流程id&发送网银返回结果").setKeys(JSON.toJSONString(dto.getId()), JSON.toJSONString(sendPay)).info();
						if(sendPay == null || !sendPay.isSuccess()){
							throw new BaseException("网银发送失败");
						}
					}else{
						while(true){
							try {
                                BaseLogUtils.newLogger("新能源拖车流程id&发送网银请求参数").setKeys(JSON.toJSONString(dto.getId())).info();
								fl.inf.facade.dto.MessageDTO<String> sendPay = bFSApiService.sendTrailCar(dto.getId());
                                BaseLogUtils.newLogger("新能源拖车流程id&发送网银返回结果").setKeys(JSON.toJSONString(dto.getId()), JSON.toJSONString(sendPay)).info();
							} catch (Exception e) {
                                BaseLogUtils.newLogger("发送还款网银错误信息").setThrowable(e).info();
								break;
							}
						}
					}
				}
				flag++;
				if(flag ==selectList.size()){
					break;
				}
			}
			break;
		
		default:
			break;
		}
		return super.executeFlowBack(flowCompleteParamsDTO);
	}
	
	/**
	 * 核查无误 
	 * @param
	 * @return
	 */
    private void getAgen(Long id) {
        List<FinPayDtlDTO> selectList = getFinPayDtlList(id);
        int flag = 0;
        for (FinPayDtlDTO dto : selectList) {
            BaseLogUtils.newLogger("网银交易查询请求参数").setBussinessId("新能源拖车流程&网银交易查询请求参数id:" + dto.getId()).info();
            InfBfsPayDTO ibpd = bFSApiService.selectByFlsNum(dto.getId());
            BaseLogUtils.newLogger("网银交易查询返回结果").setKeys(JSON.toJSONString(ibpd)).info();
            //调用网银接口
            if (null == ibpd
                    || "payFailure".equals(ibpd.getStatus())
                    || "sendFailure".equals(ibpd.getStatus())) {
                flag++;
                break;
            }
        }
        if (flag > 0) {
            if (env.equals("pro")) {
                throw new BaseException("付款失败,请点击[处理]按钮");
            }
        }
    }

	/**
	 * 处理
	 * @param
	 * @return
	 */
	private void getDeal(Long id){
		List<FinPayDtlDTO> selectList = getFinPayDtlList(id);
		int flag =0;
		for (FinPayDtlDTO dto : selectList) {
            BaseLogUtils.newLogger("新能源拖车流程网银交易查询请求参数").setBussinessId("新能源拖车流程&网银交易查询请求参数id:" + dto.getId()).info();
			InfBfsPayDTO ibpd = bFSApiService.selectByFlsNum(dto.getId());
            BaseLogUtils.newLogger("新能源拖车网银交易查询返回结果").setKeys(JSON.toJSONString(ibpd)).info();
			//调用网银接口
			if(null==ibpd
					|| "payFailure".equals(ibpd.getStatus())
					|| "sendFailure".equals(ibpd.getStatus())){
				flag ++;
				if(env.equals("pro")){
                    BaseLogUtils.newLogger("新能源拖车流程发送网银请求参数").setBussinessId("新能源拖车流程&发送网银请求参数id:" + dto.getId()).info();
					fl.inf.facade.dto.MessageDTO<String> sendPay = bFSApiService.sendTrailCar(dto.getId());
                    BaseLogUtils.newLogger("新能源拖车流程发送网银返回结果").setKeys("sendPay:" + JSON.toJSONString(sendPay)).info();
					if(sendPay == null || !sendPay.isSuccess()){
						throw new BaseException("网银发送失败");
					}
				}
			}
		}
		if(flag==0){
			if(env.equals("pro")){
				throw new BaseException("付款成功,请点击[核查无误]按钮");
			}
		}
	}
	/**
	 * 获取付款信息表
	 * @param id
	 * @return
	 */
	private List<FinPayDtlDTO> getFinPayDtlList(Long id){
		FinPayDtlQC  qc = new FinPayDtlQC();
		qc.setPayApplyId(id);
		qc.setIsDel(0L);
        BaseLogUtils.newLogger("条件查询付款明细表请求参数FinPayDtlId").setKeys(JSON.toJSONString(id)).info();
		List<FinPayDtlDTO> selectList = finPayDtlApiService.selectList(qc);

		if(CollectionUtils.isEmpty(selectList)){
			throw new BaseException("新能源拖车流程添加的付款明细数据有误,付款申请id是:"+id);
		}
		return selectList;
	}
	@Override
	public String getFlowBusinessActMgrOrgCd(FlowCompleteParamsDTO flowCompleteParamsDTO) throws BaseException {
		Long trailer_id = flowCompleteParamsDTO.getBusinessKey();
		//拖车明细数据
		List<AssTrailCarDDTO> assTrailCarDDTOList = assTrailCarApi.findTrailCarDetailListById(trailer_id).getDatas();
		String cstMgrOrgCd = "";
		if (assTrailCarDDTOList != null && assTrailCarDDTOList.size() > 0) {
			Long prjId = assTrailCarDDTOList.get(0).getPrjId();
            BaseLogUtils.newLogger("流程回调实现类获取项目客户经理组织架构代码开始").setKeys("taskId:" + flowCompleteParamsDTO.getTaskId(), "prjId:" + prjId).info();
			if(null!=prjId){
			    cstMgrOrgCd = assTrailCarDMapper.selectCstMgrOrgCd(prjId);
				if (null == cstMgrOrgCd || cstMgrOrgCd.equals("")) {
                    BaseLogUtils.newLogger("根据ID未获取到业务数据!").info();
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, "根据ID未获取到业务数据!");
				}
                BaseLogUtils.newLogger("流程回调实现类获取项目客户经理组织架构代码结束").setKeys("taskId:" + flowCompleteParamsDTO.getTaskId(), "prjId:" + prjId, "cstMgrOrgCd:" + cstMgrOrgCd).info();
				return cstMgrOrgCd;
			}
		}
        BaseLogUtils.newLogger("流程接口回调>>返回项目客户经理组织架构>>未找到!").info();
		return super.getFlowBusinessActMgrOrgCd(flowCompleteParamsDTO);
	}
	/**
	 * 流程结束:通过
	 * @param flowCompleteParamsDTO
	 * @throws BaseException
	 */
	private void pass(FlowCompleteParamsDTO flowCompleteParamsDTO)throws BaseException{
		this.sysFlowSHService.modifyAudStsCd(InterfaceConstants.ASS_FLOW_S_H_ASS, FlowConstant.FLOW_CHECK_STATE_PASS, new Date(), new Date(),
				flowCompleteParamsDTO.getCrtUsrId(), flowCompleteParamsDTO.getBusinessKey(), flowCompleteParamsDTO.getProcDefKey(), 
				flowCompleteParamsDTO.getProcDefId(), flowCompleteParamsDTO.getSysCd(), flowCompleteParamsDTO.getProcInstId());
	}
	/**
	 * 流程结束:不通过
	 * @param flowCompleteParamsDTO
	 * @throws BaseException
	 */
	private void noPass(FlowCompleteParamsDTO flowCompleteParamsDTO)throws BaseException{
		this.sysFlowSHService.modifyAudStsCd(InterfaceConstants.ASS_FLOW_S_H_ASS, FlowConstant.FLOW_CHECK_STATE_NO_PASS, new Date(), new Date(),
				flowCompleteParamsDTO.getCrtUsrId(), flowCompleteParamsDTO.getBusinessKey(), flowCompleteParamsDTO.getProcDefKey(), 
				flowCompleteParamsDTO.getProcDefId(), flowCompleteParamsDTO.getSysCd(), flowCompleteParamsDTO.getProcInstId());
	}
	/**
	 * 申请通过
	 * @param
	 * @throws BaseException
	 */
	private void flowSuccess(List<AssTrailCarDDTO> assTrailCarDDTOList)throws BaseException{
		MessageDTO<String>  result;
		for (AssTrailCarDDTO assTrailCarDDTO : assTrailCarDDTOList) {
			if (assTrailCarDDTO.getBackedFlagCd().equals(InterfaceConstants.BACK_FLAG_CD_1)) {//拖回标记：已拖回
				assTrailCarDDTO.setBackStsCd(InterfaceConstants.BACK_STATUS_CD_2);//拖车状态：已拖回
				//assTrailCarDDTO.setActBackDt(new Date());
			}
			if(assTrailCarDDTO.getBackedFlagCd().equals(InterfaceConstants.BACK_FLAG_CD_2)){//拖回标记：未拖回
				assTrailCarDDTO.setBackStsCd(InterfaceConstants.BACK_STATUS_CD_4);//拖车状态：未拖回
			}
			if(assTrailCarDDTO.getBackedFlagCd().equals(InterfaceConstants.BACK_FLAG_CD_3)){//拖回标记：无法拖回
				assTrailCarDDTO.setBackStsCd(InterfaceConstants.BACK_STATUS_CD_5);//拖车状态：无法拖回
			}
			assTrailCarDDTO.setFlowPassTm(new Date());
            BaseLogUtils.newLogger("修改拖车状态start").setKeys("detailId:" + assTrailCarDDTO.getId()).info();
			result = assTrailCarApi.updateAssTrailCarDetailInfo(assTrailCarDDTO);
			if (!result.isSuccess()) {
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "修改拖车状态失败");
			}
            BaseLogUtils.newLogger("修改拖车状态end").setKeys("detailId:" + assTrailCarDDTO.getId()).info();
		}
	}
	/**
	 * 申请不通过
	 * @param
	 * @throws BaseException
	 */
	private void flowFail(List<AssTrailCarDDTO> assTrailCarDDTOList,String procDefKey,String procInstId)throws BaseException{
		MessageDTO<String>  result;
		ProductStatusLogDTO proDTO = null;
		List<ProductStatusLogDTO> proList = new ArrayList<ProductStatusLogDTO>();
		for (AssTrailCarDDTO assTrailCarDDTO : assTrailCarDDTOList) {
			assTrailCarDDTO.setBackStsCd(InterfaceConstants.BACK_STATUS_CD_3);//拖车状态：不通过
			//修改拖车申请表中拖车状态
			result = assTrailCarApi.updateAssTrailCarDetailInfo(assTrailCarDDTO);
			if (!result.isSuccess()) {
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "修改拖车状态失败");
			}
            proDTO = new ProductStatusLogDTO();
            proDTO.setCurrentStatus(InterfaceConstants.PAY_STATUS_CD_S01);
            proDTO.setPrjPrdId(assTrailCarDDTO.getPrjPrdDtlId());
            proDTO.setOpCode(InterfaceConstants.OP_CODE_OP0019);
            proDTO.setProcessInstanceCode(procDefKey);
            proDTO.setProcessInstanceId(procInstId);
            proList.add(proDTO);
		}
        BaseLogUtils.newLogger("更新支付表状态start").info();
		result = this.assTrailCarApi.updatePayStatus(proList);
		if (!result.isSuccess()) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "更新支付表的状态失败.");
		}
        BaseLogUtils.newLogger("更新支付表状态end").info();
	}
	

	private void updatePrjPrdPaySchD(AssTrailCarDDTO assTrailCarDDTO,
			PrjPrdPaySchD prjPrdPaySchD) {
		//prjPrdPaySchD.setPaySchId(assTrailCarDDTO.getPaySchId());//支付表ID
		//prjPrdPaySchD.setPaySchNo(assTrailCarDDTO.getPaySchNo());//支付表号
		prjPrdPaySchD.setFeeAmt((double)assTrailCarDDTO.getActBackAmt());//实际拖车金额
		prjPrdPaySchD.setArAmt(assTrailCarDDTO.getActBackAmt());//未核销金额
		//prjPrdPaySchD.setFeeTypCd(InterfaceConstants.FEE_TYP_CD_104);//费用项类型
		//prjPrdPaySchD.setFeeClsCd(InterfaceConstants.FEE_CLS_CD_PRJ0040);//项目费用分类:结清
		prjPrdPaySchD.setMdfTm(new Date());//修改时间
		boolean flag = assTrailCarDMapper.updatePrjPrdPaySchD(prjPrdPaySchD);
		if (!flag) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "===更新拖车费失败===.");
		}
	}

	private Long insertPrjPrdPaySchD(AssTrailCarDDTO assTrailCarDDTO,
			PrjPrdPaySchD prjPrdPaySchD) {
		prjPrdPaySchD.setPaySchId(assTrailCarDDTO.getPaySchId());//支付表ID
		prjPrdPaySchD.setPaySchNo(assTrailCarDDTO.getPaySchNo());//支付表号
		prjPrdPaySchD.setFeeAmt((double)assTrailCarDDTO.getActBackAmt());//实际拖车金额
		prjPrdPaySchD.setFeeTypCd(InterfaceConstants.FEE_TYP_CD_104);//费用项类型
		prjPrdPaySchD.setCrtTm(new Date());
		//prjPrdPaySchD.setCrtUsrId(crtUsrId);//创建人
		prjPrdPaySchD.setPayPd(0);//期次
		prjPrdPaySchD.setIsFixedAmt(1);//是否固定金额
		prjPrdPaySchD.setCapFlow(InterfaceConstants.CAP_FLOW_1);//资金流向：收入
		prjPrdPaySchD.setCntWayCd(InterfaceConstants.CNT_WAY_CD_3);//费用计入方式：其他费用
		//prjPrdPaySchD.setPayDt(new Date());//支付时间
		//prjPrdPaySchD.setCalBaseCd();//费用计算基数
		//prjPrdPaySchD.setFeePct(feePct);//费用计算比例
		prjPrdPaySchD.setIsSysDef(1);//是否系统内置
		//prjPrdPaySchD.setFeeRem(feeRem);//备注
		prjPrdPaySchD.setArAmt(assTrailCarDDTO.getActBackAmt());//未核销金额
		//prjPrdPaySchD.setPaidUpAmt(paidUpAmt);//已核销金额
		//prjPrdPaySchD.setIsModify(isModify);//是否修改
		prjPrdPaySchD.setIsDel(0);//是否删除
		prjPrdPaySchD.setVersion(0L);//版本号
		prjPrdPaySchD.setMdfTm(new Date());//修改时间
		//prjPrdPaySchD.setMdfUsrId(mdfUsrId);//修改人
		prjPrdPaySchD.setFeeClsCd(InterfaceConstants.FEE_CLS_CD_PRJ0040);//项目费用分类:结清
		Long id = assTrailCarDMapper.insertPrjPrdPaySchD(prjPrdPaySchD);
		return id;
	}

    /**
     * 核查无误后自动通过放款中节点
     * 流程实例ID
     * @param procInstId
     */
    private void passPay(String procInstId, Map<String, Object> params, String taskDefKey){
        com.lionbridge.activiti.dto.MessageDTO<String> dto = WorkflowClient.completeTaskByTaskDefKey(
                procInstId
                , taskDefKey, params);
        BaseLogUtils.newLogger("核查无误后自动通过放款中节点").setKeys("dto:" + JSON.toJSONString(dto)).info();
    }

}
